package com.operate.task;

import com.alibaba.fastjson2.JSONObject;
import com.operate.bean.VO.CustomNumVO;
import com.operate.bean.VO.Fields;
import com.operate.config.HttpConfig;
import com.operate.service.ScreenDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: ZZZ
 * @time: 2023/11/3 21:36
 */
@Slf4j
@Service
public class CustomNumTask {


    @Value("${custom.enable}")
    private boolean enable;

    @Value("${custom.query.url}")
    private String query_url;

    @Value("${custom.delete.url}")
    private String delete_url;

    @Value("${custom.insert.url}")
    private String insert_url;

    @Autowired
    private ScreenDataService service;
    @Autowired
    private HttpConfig httpConfig;


    @Async("myAsync")
    public void customNumTask() {
        if (enable == false) {
            log.info("Custom Num Task  未开启");
            return;
        }
        LocalDateTime s = LocalDateTime.now();
        //客户数统计（近12个月）
        List<CustomNumVO> list = service.customNum();
        LocalDateTime sqlExeTime = LocalDateTime.now();
        httpConfig.clearData(query_url, delete_url);


        if (list != null && !list.isEmpty()) {

            List<Fields> insertList = new ArrayList<>();
            for (CustomNumVO vo : list) {
                Fields fields = new Fields(vo);
                insertList.add(fields);
            }
            Map<String, List<Fields>> insertMap = new HashMap<>();
            insertMap.put("records", insertList);

            String insertResult = httpConfig.POST(insert_url, JSONObject.toJSONString(insertMap));
            LocalDateTime e = LocalDateTime.now();
            long sqlTime = Duration.between(s, sqlExeTime).getSeconds();
            long seconds = Duration.between(s, e).getSeconds();
            log.info("Custom Num Task 总耗时{}秒(SQL 耗时{}) 插入{}条记录 插入结果: {}", seconds, sqlTime, list.size(), insertResult);

        }
    }
}


